#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : aimix
@File    : video_synthesis_worker.py
@IDE     : PyCharm
@Author  : admin
@Date    : 2025/4/22 09:40
"""
import json
import os.path
import traceback
from core.video.clip import *
from PyQt5.QtCore import pyqtSignal, QThread

from core.video.normal_synthesis import NormalVideoSynthesis
from core.video.auto_synthesis import AutoSynthesis
from utils.load_file import load_files


class VideoSynthesisWorker(QThread):
    """视频合成线程"""
    failed = pyqtSignal(Exception)


    def __init__(self, params, parent=None):
        super(VideoSynthesisWorker, self).__init__()
        self.params = params

    def run(self):
        try:
            params = json.loads(self.params)
            channels = params.get("channels")
            video_groups = params.get("video_groups")
            num_outputs = params.get("num_outputs")
            import_subtitle = params.get("import_subtitle")
            subtitle_path = params.get("subtitle_path")
            keep_original_audio = params.get("keep_original_audio")
            auto_match_audio = params.get("auto_match_audio")
            audio_path = params.get("audio_path")
            audio_status = params.get("audio_status")
            total_duration = params.get("total_duration")
            speed = params.get("speed")
            output_dir = params.get("output_dir")
            video_priority = params.get("video_priority")
            resolution = eval(params.get("resolution"))
            set_title = params.get("set_title")
            set_background_music = params.get("set_background_music")
            set_overlay = params.get("set_overlay")
            set_cover = params.get("set_cover")
            set_watermark = params.get("set_watermark")
            set_filters = params.get("set_filters")
            kwargs = params.get("kwargs")

            if channels == 'auto':
                AutoSynthesis(
                    video_groups=video_groups,
                    num=params.get("num"),
                    rule=params.get("rule"),
                    times=params.get("times"),
                    select_rule=params.get("select_rule", "random"),
                    num_outputs=num_outputs,
                    import_subtitle=import_subtitle,
                    subtitle_path=subtitle_path,
                    keep_original_audio=keep_original_audio,
                    auto_match_audio=auto_match_audio,
                    audio_path=audio_path,
                    audio_status=audio_status,
                    total_duration=total_duration,
                    speed=speed,
                    output_dir=output_dir,
                    video_priority=video_priority,
                    resolution=resolution,
                    set_title=set_title,
                    set_background_music=set_background_music,
                    set_overlay=set_overlay,
                    set_cover=set_cover,
                    set_watermark=set_watermark,
                    set_filters=set_filters,
                    **kwargs).generate()

            else:
                for v in video_groups:
                    if isinstance(v.get("files"), str):
                        if os.path.isdir(v.get("files")):
                            v["files"] = load_files(v.get("files"))
                        elif os.path.isfile(v.get("files")):
                            v["files"] = [v.get("files")]
                        else:
                            raise ValueError("文件路径错误")

                    elif isinstance(v.get("files"), list):
                        for f in v.get("files"):
                            if not os.path.isfile(f):
                                raise ValueError("文件路径错误")
                    else:
                        raise ValueError("文件错误")
                NormalVideoSynthesis(
                    video_groups=video_groups,
                    num_outputs=num_outputs,
                    import_subtitle=import_subtitle,
                    subtitle_path=subtitle_path,
                    keep_original_audio=keep_original_audio,
                    auto_match_audio=auto_match_audio,
                    audio_path=audio_path,
                    audio_status=audio_status,
                    total_duration=total_duration,
                    speed=speed,
                    output_dir=output_dir,
                    video_priority=video_priority,
                    resolution=resolution,
                    set_title=set_title,
                    set_background_music=set_background_music,
                    set_overlay=set_overlay,
                    set_cover=set_cover,
                    set_watermark=set_watermark,
                    set_filters=set_filters,
                    **kwargs
                ).generate()

        except Exception as e:
            self.failed.emit(e)
            traceback.print_exc()